import React, { memo, useState } from "react";
import type { FC, ReactNode } from "react";
import { UserNameWrapper } from "./style";
import { useAppDispatch, useAppSelector } from "@/store";
import { feachChangeUserInfoAction, feachSearchKeywordsAction } from "@/store/modules/login";
import { shallowEqual } from "react-redux";
import { formatUrlSize } from "@/utils/format";
import classNames from "classnames";
import { useNavigate } from "react-router-dom";
import { notification } from "antd";
import { CheckCircleOutlined } from "@ant-design/icons";

interface IProps {
  children?: ReactNode;
}

const UserName: FC<IProps> = () => {
  const dispatch = useAppDispatch()
  const handlekeyDown = async (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.code === "Enter") {
      dispatch(feachSearchKeywordsAction(event.currentTarget.value))
    }
  }
  const [currIndex, setCurrindex] = useState(0)

  const { searchUsers } = useAppSelector((state) => ({
    searchUsers: state.login.searchUsers
  }), shallowEqual)

  const handleUserClick = (index: number) => {
    setCurrindex(index)
  }

  const [api] = notification.useNotification();
  const navigate = useNavigate()
  const handleNotarize = () => {
    dispatch(feachChangeUserInfoAction({ modeType: "UserName", userInfo: searchUsers[currIndex] }))
    // 跳转到我们的 发现页面
    navigate("/musiclibrary")
    api.info({
      message: "用户名登录成功🦌",
      description: "欢迎回家👉",
      icon: <CheckCircleOutlined style={{ color: '#108ee9' }} />,
      placement: "topRight",
    });

  }
  return <UserNameWrapper>
    <div className="userName-header">
      用户名登录
    </div>
    <div className="userName-search">
      <div className="search-icon">
        <img src={require("@/assets/img/search-icon.png")} alt="" />
      </div>
      <input type="text" className="userName-ipt" placeholder="请输入您的网易云用户名" onKeyDown={e => handlekeyDown(e)} />
    </div>
    {searchUsers.length <= 0 && <div className="userName-text">按 Enter 搜索</div>}
    {searchUsers.length > 0 && <div className="userName-text">在列表中选中你的账号: </div>}
    {searchUsers.length > 0 && <div className="search-userList">
      {
        searchUsers.map((item, index) => (
          <div className={classNames("search-user", { searchUseRactive: index === currIndex })} onClick={() => handleUserClick(index)} key={item.userId}>
            <img src={formatUrlSize(item.avatarUrl, 120)} alt="用户头像" className="search-cover" />
            <div className="nike-name">{item.nickname}</div>
          </div>
        ))
      }
    </div>}
    {searchUsers.length > 0 && <div className="button-notarize" onClick={handleNotarize}>确认</div>}
  </UserNameWrapper>;
};

export default memo(UserName);